package com.shahe.GirlsDay;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.concurrent.ExecutionException;

import org.apache.http.HttpResponse;
import org.json.JSONException;

import com.shahe.GirlsDay.util.HttpHelper;
import com.shahe.GirlsDay.util.StaticClass;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.*;

/**
 * Created by Sarah on 7/06/2014.
 */
public class RegisterActivity extends Activity {
	/**
	 * Called when the activity is first created.
	 */

	private Spinner spinner;
	private EditText givennameEdit;
	private EditText surnameEdit;
	private EditText usernameEdit;
	private EditText passwordEdit;
	private EditText emailEdit;
	private EditText phoneEdit;
	private EditText cpnameEdit;
	private EditText cpphoneEdit;
	private EditText cpemailEdit;
	private int i = 0;
	private int j = 0;

	private boolean checkUsername = false;

	final static int WRAP_CONTENT = -2;
	int[] msgIds = { R.string.relationship00, R.string.relationship01,
			R.string.relationship02, R.string.relationship03,
			R.string.relationship04 };

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.registerpage);

		final Button cancelButton = (Button) findViewById(R.id.btn_reg_cancel);
		final Button createButton = (Button) findViewById(R.id.btn_reg_create);
		final Button checkButton = (Button) findViewById(R.id.btn_reg_check);

		givennameEdit = (EditText) findViewById(R.id.et_given_name);
		surnameEdit = (EditText) findViewById(R.id.et_surname);
		usernameEdit = (EditText) findViewById(R.id.et_user_name);
		passwordEdit = (EditText) findViewById(R.id.et_psw);
		emailEdit = (EditText) findViewById(R.id.et_email);
		cpnameEdit = (EditText) findViewById(R.id.et_co_name);
		cpphoneEdit = (EditText) findViewById(R.id.et_co_phoneNO);
		cpemailEdit = (EditText) findViewById(R.id.et_co_email);

		getWindow().setSoftInputMode(
				WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
		spinner = (Spinner) this.findViewById(R.id.reg_spinner);
		BaseAdapter baseAdapter = new BaseAdapter() {
			@Override
			public int getCount() {
				return 5;
			}

			@Override
			public Object getItem(int position) {
				return null;
			}

			@Override
			public long getItemId(int position) {
				return 0;
			}

			@Override
			public View getView(int position, View convertView, ViewGroup parent) {
				LinearLayout linearLayout = new LinearLayout(
						RegisterActivity.this);
				linearLayout.setOrientation(LinearLayout.HORIZONTAL);
				// linearLayout.setBackgroundColor(getResources().getColor(R.color.black));

				TextView textView = new TextView(RegisterActivity.this);
				textView.setText("" + getResources().getText(msgIds[position]));
				textView.setTextSize(22);
				// textView.setBackgroundColor(getResources().getColor(R.color.title_color));
				textView.setTextColor(getResources().getColor(
						R.color.word_color));
				linearLayout.addView(textView);

				return linearLayout;
			}
		};
		spinner.setAdapter(baseAdapter);

		// spinner.getSelectedItemPosition();

		// updateDetails

		if (StaticClass.myInfo.getUserid() != 0) {
			givennameEdit.setText(StaticClass.myInfo.getGivenname());
			surnameEdit.setText(StaticClass.myInfo.getSurname());
			usernameEdit.setText(StaticClass.myInfo.getUsername());
			usernameEdit.setEnabled(false);
			passwordEdit.setText(StaticClass.myInfo.getPassword());
			emailEdit.setText(StaticClass.myInfo.getEmail());
			if (StaticClass.cPersonInfo.getContactid() != 0) {
				cpnameEdit.setText(StaticClass.cPersonInfo.getContactname());
				cpphoneEdit.setText(StaticClass.cPersonInfo.getPhone());
				cpemailEdit.setText(StaticClass.cPersonInfo.getEmail());
				spinner.setSelection(Integer.valueOf(StaticClass.cPersonInfo
						.getRelationship()));
				TextView textView = (TextView) findViewById(R.id.tv_reg_title);
				textView.setText("Account");
				createButton.setText("Change");
			}

		}

		checkButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				String newUsername = usernameEdit.getText().toString();
				// warring(newUsername);
				if (checkInput(newUsername)) {
					String json = null;
					try {
						json = new checkTask().execute(newUsername).get();
						// warring(json);
					} catch (InterruptedException | ExecutionException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						warring("Can't connect to server");
					}
					if (json.length() == 2) {
						warring("Username can be used!");
						String newUserId = "0";
						String newCPId = "0";
						try {

							newUserId = new getNewIdTask().execute("try").get();
							// warring(newUserid);
							i = Integer.valueOf(newUserId) + 1;
							usernameEdit.setEnabled(false);
							warring(i + "");

							newCPId = new getCPIdTask().execute("try").get();
							j = Integer.valueOf(newCPId) + 1;

						} catch (InterruptedException | ExecutionException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
							warring("Can't connect to server");
						}
					} else {
						warring("Invalid Username");
					}

				}
			}
		});

		cancelButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});

		createButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {

				if (i != 0) {
					// userinfo
					StaticClass.myInfo.setUserid(i);
					StaticClass.myInfo.setUsername(usernameEdit.getText()
							.toString());
					StaticClass.myInfo.setGivenname(givennameEdit.getText()
							.toString());
					StaticClass.myInfo.setSurname(surnameEdit.getText()
							.toString());
					StaticClass.myInfo.setGivenname(givennameEdit.getText()
							.toString());
					StaticClass.myInfo.setSurname(surnameEdit.getText()
							.toString());
					StaticClass.myInfo.setPassword(passwordEdit.getText()
							.toString());
					StaticClass.myInfo.setEmail(emailEdit.getText().toString());
					StaticClass.myInfo.setOvulation("11");
					StaticClass.myInfo.setCycledays("35");
					StaticClass.myInfo.setDefaultlength("7");

					// updateUserInfo
					try {
						String statusCode = new postUserInfoTask().execute(
								StaticClass.myInfo.toJson().toString()).get();
						warring(statusCode);
					} catch (InterruptedException | ExecutionException
							| JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

					// cpinfo

					if (!cpnameEdit.getText().toString().equals(null)
							&& !cpphoneEdit.getText().toString().equals(null)
							&& !cpemailEdit.getText().toString().equals(null)) {
						StaticClass.cPersonInfo.setUserid(i);
						StaticClass.cPersonInfo.setContactid(j);
						StaticClass.cPersonInfo.setContactname(cpnameEdit
								.getText().toString());
						StaticClass.cPersonInfo.setRelationship(String
								.valueOf(spinner.getSelectedItemPosition()));
						StaticClass.cPersonInfo.setPhone(cpphoneEdit.getText()
								.toString());
						StaticClass.cPersonInfo.setEmail(cpemailEdit.getText()
								.toString());

						// update

						try {
							String statusCode = new postCPInfoTask()
									.execute(
											StaticClass.cPersonInfo.toJson()
													.toString()).get();
						} catch (InterruptedException | ExecutionException
								| JSONException e) {
							// TODO Auto-generated catch block
							// e.printStackTrace();
						}

					} else {
						warring("You didn't fill a contact person!");
					}

					// StaticClass.cPersonInfo

					if (StaticClass.createOrChang == false) {
						StaticClass.createOrChang = true;
						Intent intent = new Intent(RegisterActivity.this,
								HomeActivity.class);
						startActivity(intent);
					} else {
						finish();
					}
				}

				// StaticClass.myInfo.set

				// warring(String.valueOf(spinner.getSelectedItemPosition()));

				// warring( StaticClass.myInfo.getUserid()+ "");

				// finish();

			}
		});

	}

	private class checkTask extends AsyncTask<String, String, String> {

		protected String doInBackground(String... strings) {
			return HttpHelper.checkUsername(strings[0]);
		}

		protected void onPostExecute(String result) {
			super.onPostExecute(result);
		}

	}

	private class getNewIdTask extends AsyncTask<String, String, String> {

		protected String doInBackground(String... strings) {
			return HttpHelper.getUserId(strings[0]);
		}

		protected void onPostExecute(String result) {
			super.onPostExecute(result);
		}

	}

	private class getCPIdTask extends AsyncTask<String, String, String> {

		protected String doInBackground(String... strings) {
			return HttpHelper.getCPersonId(strings[0]);
		}

		protected void onPostExecute(String result) {
			super.onPostExecute(result);
		}

	}

	public boolean checkInput(String str) {
		if (str.matches("^\\w+?")) {
			return true;
		} else if (str.equals(null)) {
			Toast.makeText(this, "null", Toast.LENGTH_LONG).show();
			return false;
		} else {
			warring("format error");
			return false;
		}
	}

	public void warring(String str) {
		Toast.makeText(this, str, Toast.LENGTH_LONG).show();
	}

	private class postUserInfoTask extends AsyncTask<String, String, String> {

		protected String doInBackground(String... strings) {
			return (HttpHelper.postUserInfo(strings[0]) + "");
		}

		protected void onPostExecute(String result) {
			super.onPostExecute(result);
		}

	}

	private class postCPInfoTask extends AsyncTask<String, String, String> {

		protected String doInBackground(String... strings) {
			return HttpHelper.postCPInfo(strings[0]) + "";
		}

		protected void onPostExecute(String result) {
			super.onPostExecute(result);
		}

	}

}
